import { _decorator, Component, Node, Vec2 } from 'cc';
import { playerState } from './playerState';
import { ENTITY_STATE_ENUM } from '../../Enum';
import { InputManager } from '../../Base/InputManager';
const { ccclass, property } = _decorator;

@ccclass('WallJumpState')
export class WallJumpState extends playerState {
    private _lastWallJumpDir: number = 0;
    onEnter(): void {
        super.onEnter();
        
    }

    update(deltaTime: number): void {
        
        // 松开跳跃键
        if (!InputManager.Instance.pressJump) {
            this.fsm.setGravityScale(this.fsm.player.data.gravityScale * this.fsm.player.data.jumpCutGravityMult);
            this.rb.linearVelocity = new Vec2(
                this.rb.linearVelocity.x,
                Math.max(this.rb.linearVelocity.y, -this.fsm.player.data.maxFallSpeed)
            );
        }else if (Math.abs(this.rb.linearVelocity.y) < this.fsm.player.data.jumpHangTimeThreshold) {
            this.fsm.setGravityScale(this.fsm.player.data.gravityScale * this.fsm.player.data.jumpHangGravityMult);
        } 

        super.update(deltaTime); 

        // 跳跃下落检测
        if (this.rb.linearVelocity.y < 0) {
            this.fsm.transit(ENTITY_STATE_ENUM.FALL)        
        }

        this.run(this.fsm.player.data.wallJumpRunLerp);
    }

    *Coroutine(): Generator {
        // yield null;

        this.fsm.setGravityScale(this.fsm.player.data.gravityScale);

        this._lastWallJumpDir = (this.fsm.lastOnWallRightTime > 0) ? -1 : 1;

        this.fsm.lastPressedJumpTime = 0;
        this.fsm.lastOnGroundTime = 0;
        this.fsm.lastOnWallRightTime = 0;
        this.fsm.lastOnWallLeftTime = 0;

        const force = new Vec2(
            this.fsm.player.data.wallJumpForce.x * this._lastWallJumpDir,
            this.fsm.player.data.wallJumpForce.y
        );
        // 抵消向下速度
        if (this.rb.linearVelocity.x < 0) {
            this.rb.linearVelocity = new Vec2(0, this.rb.linearVelocity.y);
        }
        if (this.rb.linearVelocity.y < 0) {
            this.rb.linearVelocity = new Vec2(this.rb.linearVelocity.x, 0); 
        }
        this.rb.applyForceToCenter(force, true);

    }
    IsCoroutine(): boolean {
        return true;
    }

    onExit(): void {
        super.onExit(); 
    }

    canTransit(to: ENTITY_STATE_ENUM): boolean {
        if(to === this.id) return false;
        if(to === ENTITY_STATE_ENUM.DASH) return true;
        if(this.stateTime > this.fsm.player.data.wallJumpTime) return true;
        return false;
    }
}


